package com.alumni_circle.core.utils;

import com.alumni_circle.core.entity.rbac.LoginUser;
import com.alumni_circle.entity.me.User;
import com.alumni_circle.entity.me.VO.UserViewVO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * SecurityContextHolder.getContext().getAuthentication().getPrincipal()获取当前用户工具类
 *
 * @author  龙小虬
 * @create  2020-08-14 10:34
 **/
public class SecurityUtils {
    /**
     * 获取用户 username
     **/
    public static String getUsername() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            throw e;
        }
    }

    public static String getRole(){
        try{
            return getLoginUser().getUser().getRole();
        }catch (Exception e){
            throw e;
        }
    }

    /**
     * 获取用户id
     * @return
     */
    public static String getId(){
        try {
            return getLoginUser().getUser().getId();
        }catch (Exception e){
            throw e;
        }
    }

    /**
     * 获取用户的社团名称
     * @return
     */
    public static String getClubName(){
        try {
            return getLoginUser().getUser().getClub();
        }catch (Exception e){
            throw e;
        }
    }

    /**
     * 获取用户名称
     *
     * @return
     */
    public static String getName() {
        try {
            return getLoginUser().getUser().getName();
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw e;
        }
    }

    public static User getUser(){
        try {
            return getLoginUser().getUser();
        } catch (Exception e) {
            throw e;
        }
    }

    public static String getPostId(){
        System.out.println((getAuthentication().getDetails()));
        return "success";
    }

    /**
     * 获取用户基本信息
     * @return
     */
    public static UserViewVO getUserInfo(){
        try {
            return ModelUtils.transform(getLoginUser().getUser(), UserViewVO.class);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

}
